package guiMVC;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import reader.InstanceReader;
import value_object.InstanceVO;
import value_object.ResultVO;
import value_object.SolutionVO;
import factory.ResultFactory;
import factory.SolutionFactory;

public class Controller implements ActionListener {
	private Model model = Model.getModel();
    private View view;
    
	public Controller(View view) {
		this.view = view;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
        
		if (source.equals(view.getBtnGetInstance())) {
        	updateModel_Intance();
        	return;
        }
		
		if (source.equals(view.getBtnGetSolution())) {
        	updateModel_Solution();
        	return;
        }
		
		if (source.equals(view.getBtnGetResult())) {
			updateModel_Result();
        	return;
        }
		
		if (source.equals(view.getChbViewInDetail())) {
			updateModel_ViewInDetail();
        	return;
        }
	}
	
	private void updateModel_Intance() {
		int data_set_number = Integer.parseInt(view.getTxtData_set_number().getText());
		int grid_number = Integer.parseInt(view.getTxtGrid_number().getText());
		int track_number = Integer.parseInt(view.getTxtTrack_number().getText());
		
		InstanceReader instanceReader = new InstanceReader();
		InstanceVO instance = new InstanceVO();
		try {
			instance = instanceReader.readInstance(data_set_number, grid_number, track_number);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println(instance);
		model.updateModel(instance);
	}
	
	private void updateModel_Solution() {
		SolutionFactory solutionFac = new SolutionFactory(model.getInstance());
		SolutionVO solution = solutionFac.getSolution();
		
		System.out.println(solution);
		model.updateModel(solution);
	}
	
	private void updateModel_Result() {
		ResultFactory resultFac = new ResultFactory(model.getInstance());
		ResultVO result = resultFac.getResult(model.getSolution());
		
		System.out.println(result);
		model.updateModel(result);
	}
	
	private void updateModel_ViewInDetail() {
		model.updateModel(view.getChbViewInDetail().isSelected());
	}
}
